package com.ruoyi.standingbook.v2toilet.logic;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.standingbook.v2toilet.ToiletConst;
import com.ruoyi.standingbook.v2toilet.bill.BillFlowUtil;
import com.ruoyi.standingbook.v2toilet.bill.BillSendBean;
import com.ruoyi.standingbook.v2toilet.domain.bo.V2ToiletBillBo;
import com.ruoyi.standingbook.v2toilet.domain.bo.V2ToiletBo;
import com.ruoyi.standingbook.v2toilet.domain.vo.V2ToiletBillVo;
import com.ruoyi.standingbook.v2toilet.enums.ItemStatusEnum;
import com.ruoyi.standingbook.v2toilet.mapper.ApiLogMapper;
import com.ruoyi.standingbook.v2toilet.service.IToiletBillService;
import com.ruoyi.standingbook.v2toilet.service.IToiletService;
import com.ruoyi.stat.toilet.logic.HttpLogic;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class V2ExtendAsyncService {
    private final ISysOssService iSysOssService;
    private final ApiLogMapper apiLogMapper;
    private final IToiletBillService billService;
    private final IToiletService toiletService;
    private final ISysConfigService configService;


    @Async
    public void saveApiLog(String callMethod, boolean out, String body) {
        //        (id,create_time,title,data)  values  (#{id},#{time},#{title},#{data})
        String prefix = DateUtil.now();
        prefix = prefix.concat("-").concat(out ? "SEND" : "RECEIVE");
        log.info("length:-->prefix:{}，body:{}", prefix.length(), body.length());
        Map<String, Object> data = new HashMap<>();
        data.put("id", IdUtil.fastSimpleUUID());
        data.put("time", new Date());
        data.put("title", prefix.concat(callMethod));
        data.put("url", "");
        data.put("params", "");
        data.put("data", body);

        apiLogMapper.saveApiLog(data);
    }


    @Async
    public void sendBills() {
        //找到错的
        List<BillSendBean> pullData = billService.querySendValue(new V2ToiletBillBo(ItemStatusEnum.ERR));
        if (pullData.isEmpty()) return;
        //符合条件的流水号
        List<String> flowCodes = pullData.stream().map(BillSendBean::getFlowCode).collect(Collectors.toList());//ID集合
        //按厕所分组
        Map<String, List<BillSendBean>> groupMap = pullData.stream().collect(Collectors.groupingBy(BillSendBean::getToiletId, Collectors.toList()));
        Set<String> keys = groupMap.keySet();
        Map<String, Object> issues = new HashMap<>();
        List<Map<String, Object>> items = new ArrayList<>();
        for (String key : keys) {
            Map<String, Object> regions = new HashMap<>();
            BillSendBean data = groupMap.get(key).get(0);
            regions.put("region_name", data.getCommunity());
            regions.put("place_name", data.getToiletName());
            regions.put("inspection_time", DateUtil.format(data.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            regions.put("inspection_username", data.getCurrUser());
            regions.put("issue", groupMap.get(key));
            items.add(regions);
            issues.put("project_name", data.getProjectName());
        }
        issues.put("issue_list", items);
        String sendData = JSONUtil.toJsonStr(issues);
        log.info("api.bill.send >>>>>{}", sendData);
        //        apiLogService.saveApiLog(true, false, sendData);
        JSONObject respData;
        Integer code;
        String url = "/workspace/elec/inspection/ticketsImport";
        try {
            String response = HttpLogic.postBody(configService, url, sendData);
            respData = JSONUtil.parseObj(response);
            code = respData.get("code", Integer.class, true);
            //记录下返回结果
            if (code == 0) {
                //更新表，设置状态为提交 同时设定重复导入后 不可以更新
                billService.updateByFlowCode(ItemStatusEnum.COMMIT, flowCodes);
            } else {
                this.saveApiLog("V2ExtendAsyncService.sendBills", false, respData.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.saveApiLog("V2ExtendAsyncService.sendBills", false, e.getMessage());
        }


    }

    /**
     * @param name name 要给值看业务场景
     * @param url  原始图片地址
     * @return 系统图片信息
     */
    public SysOss bytesUpload(String name, String url) {
        byte[] bytes = HttpUtil.downloadBytes(url);
        if (Objects.isNull(bytes))
            return null;
        name = name.concat(FileNameUtil.getSuffix(url));
        return iSysOssService.bytesUpload(bytes, name);
    }

    @Async
    public void updateProcessUser() {
        //找状态1的
        V2ToiletBillBo bo = new V2ToiletBillBo(ItemStatusEnum.COMMIT);
        bo.setModified(ItemStatusEnum.COMMIT.intCode);
        V2ToiletBillVo vo = billService.queryOne(bo);
        if (Objects.isNull(vo))
            return;
        bo = BeanCopyUtils.copy(vo, V2ToiletBillBo.class);
        if (Objects.isNull(bo))
            return;
        //找到状态是0的
        List<BillSendBean> pullData = billService.querySendValue(null);
        JSONObject params = JSONUtil.createObj();
        params.set("tickets_no", vo.getFlowCode());
        //json.set("tickets_no", "GD202306142045294596");
        String url = "/workspace/elec/inspection/inspectionInfo";
        String resp = HttpLogic.getBody(configService, url, params.toString());
        JSONObject json = JSONUtil.parseObj(resp);
        int code = json.getInt("code");
        if (code == 0) {
            List<String> userList = new ArrayList<>();
            JSONObject handler_user_list = json.getJSONObject("data").getJSONObject("handler_user_list");
            Set<String> keys = handler_user_list.keySet();
            handler_user_list.forEach((a, b) -> {
                userList.add(JSONUtil.parseObj(b).getStr("user_name", ""));
            });
            String strUser = String.join(",", userList);
            bo.setCurrUser(strUser);
            BillFlowUtil.setFlow(bo);
            bo.setStatus(null);//用了要设置到正常流程
            bo.setModified(ToiletConst.MODIFY_NOT);
            billService.updateByBo(bo);
            V2ToiletBo toiletBo = new V2ToiletBo();
            toiletBo.setModified(ToiletConst.MODIFY_NOT);
            toiletBo.setId(bo.getToiletId());
            toiletService.updateByBo(toiletBo);
        } else {
            saveApiLog("V2ExtendAsyncService.updateProcessUser code!=0", true, bo.getFlowCode().concat("---").concat(resp));
        }

    }

    @Async
    public void sendOneBill() {
        //        V2ToiletBillVo vo = iToiletBillService.queryOne(new V2ToiletBillBo(BillStatusEnum.INIT));
        //        if (Objects.isNull(vo))
        //            return;
        //        V2ToiletBillBo bo = BeanCopyUtils.copy(vo, V2ToiletBillBo.class);
        //        if (Objects.isNull(bo))
        //            return;
        //        //找到状态是0的
        //        List<BillSendBean> pullData = iToiletBillService.querySendValue(null);
        //        JSONObject json = new JSONObject();
        //        json.set("tickets_no", vo.getFlowCode());
        //        String resp = HttpLogic.getBody("/workspace/elec/inspection/inspectionInfo?tickets_no=GD202306142045294596", json.toString());
        //        json = JSONUtil.parseObj(resp);
        //        int code = json.getInt("code");
        //        if (code == 0) {
        //            List<String> user = new ArrayList<>();
        //            JSONObject handler_user_list = json.getJSONObject("data").getJSONObject("handler_user_list");
        //            Set<String> keys = handler_user_list.keySet();
        //            handler_user_list.forEach((a, b) -> {
        //                user.add(JSONUtil.parseObj(b).get("user_name", String.class, true));
        //            });
        //            System.out.println(String.join(",", user));
        //            bo.setCurrUser(String.join(",", user));
        //            BillFlowUtil.setFlow(bo);
        //            iToiletBillService.updateByBo(bo);
        //        }

    }

}
